﻿using MySql.Data.MySqlClient;
using System;
using System.Windows.Forms;

namespace Связь_с_БД
{
    public partial class FormLogin : Form
    {
        public FormLogin()
        {
            InitializeComponent();
        }

        private void Button2Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Button1Click(object sender, EventArgs e)
        {
            if(IsCorrectUserPassword())
            {
                var form = Owner as FormMain;
                if (form != null)
                {
                    form.SetUserId(textBox1.Text);
                    form.SetPassword(textBox2.Text);
                    form.SetServer(textBox3.Text);
                    form.SetNameBd(textBox4.Text);
                    form.QueryAll();
                    form.Visible = true;
                    Close();
                }
            }
        }

        private bool IsCorrectUserPassword()
        {
            string connect = string.Format("Database={0};Data Source={1};User Id={2};Password={3};",textBox4.Text,textBox3.Text,textBox1.Text, textBox2.Text);
            MySqlConnection connection = new MySqlConnection(connect);
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                if (ex.Message.Contains("password") || ex.Message.Contains("user"))
                {
                    MessageBox.Show(@"Неверный логин или пароль", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return false;
        }
    }
}
